<template>
  <q-page class="q-pa-md">
    <!-- 查询表单 -->
    <q-card flat bordered class="q-mb-md">
      <q-card-section>
        <div class="text-h6">配置查询</div>
      </q-card-section>
      <q-card-section>
        <q-form @submit="handleSearch" class="row q-col-gutter-md">
          <q-input
            v-model="searchForm.configName"
            label="参数名称"
            outlined
            dense
            clearable
            class="col-md-4 col-sm-6 col-xs-12"
          />
          <q-input
            v-model="searchForm.configKey"
            label="参数键名"
            outlined
            dense
            clearable
            class="col-md-4 col-sm-6 col-xs-12"
          />
          <q-select
            v-model="searchForm.configType"
            label="系统内置"
            :options="configTypeOptions"
            outlined
            dense
            emit-value
            map-options
            class="col-md-4 col-sm-6 col-xs-12"
          />
          <div class="col-md-12 flex justify-end">
            <q-btn type="submit" color="primary" label="查询" class="q-mr-sm" />
            <q-btn @click="resetSearch" label="重置" outline color="primary" />
          </div>
        </q-form>
      </q-card-section>
    </q-card>

    <!-- 操作按钮和表格 -->
    <q-card flat bordered>
      <q-card-section class="row items-center">
        <div class="text-h6 col">配置列表</div>
        <div class="col-auto q-gutter-sm">
          <q-btn color="primary" label="新增配置" icon="add" @click="showAddDialog" />
          <q-btn
            color="negative"
            label="批量删除"
            icon="delete"
            :disable="selected.length === 0"
            @click="confirmBatchDelete"
          />
          <q-btn color="grey" label="导出" icon="download" @click="exportData" />
          <q-btn color="secondary" label="刷新缓存" icon="cached" @click="refreshCache" />
        </div>
      </q-card-section>

      <!-- 数据表格 -->
      <q-table
        v-model:selected="selected"
        :rows="configs"
        :columns="columns"
        row-key="configId"
        :loading="loading"
        :pagination="pagination"
        @request="onRequest"
        selection="multiple"
        binary-state-sort
        flat
        bordered
      >
        <!-- 系统内置列 -->
        <template v-slot:body-cell-configType="props">
          <q-td :props="props">
            <q-badge :color="props.row.configType === 'Y' ? 'positive' : 'grey'">
              {{ props.row.configType === 'Y' ? '是' : '否' }}
            </q-badge>
          </q-td>
        </template>

        <!-- 操作列 -->
        <template v-slot:body-cell-actions="props">
          <q-td :props="props" class="q-gutter-x-sm">
            <q-btn
              dense
              color="primary"
              icon="edit"
              @click="showEditDialog(props.row)"
              :disable="props.row.configType === 'Y'"
            >
              <q-tooltip>{{
                props.row.configType === 'Y' ? '系统内置不可编辑' : '编辑'
              }}</q-tooltip>
            </q-btn>
            <q-btn
              dense
              color="negative"
              icon="delete"
              @click="confirmDelete(props.row.configId)"
              :disable="props.row.configType === 'Y'"
            >
              <q-tooltip>{{
                props.row.configType === 'Y' ? '系统内置不可删除' : '删除'
              }}</q-tooltip>
            </q-btn>
          </q-td>
        </template>
      </q-table>
    </q-card>

    <!-- 新增/编辑对话框 -->
    <q-dialog v-model="dialogVisible" persistent>
      <q-card style="min-width: 600px">
        <q-card-section>
          <div class="text-h6">{{ isEdit ? '编辑配置' : '新增配置' }}</div>
        </q-card-section>

        <q-card-section class="q-pt-none">
          <q-form @submit="submitForm" class="q-gutter-md">
            <q-input
              v-model="configForm.configName"
              label="参数名称"
              :rules="[(val) => !!val || '参数名称不能为空']"
              outlined
            />

            <q-input
              v-model="configForm.configKey"
              label="参数键名"
              :rules="[(val) => !!val || '参数键名不能为空']"
              outlined
              :readonly="isEdit"
            />

            <q-input
              v-model="configForm.configValue"
              label="参数键值"
              :rules="[(val) => !!val || '参数键值不能为空']"
              outlined
            />

            <q-select
              v-model="configForm.configType"
              label="系统内置"
              :options="configTypeOptions"
              outlined
              emit-value
              map-options
              :disable="isEdit"
            />

            <q-input v-model="configForm.remark" label="备注" type="textarea" outlined autogrow />

            <div class="flex justify-end q-gutter-sm">
              <q-btn label="取消" v-close-popup flat color="primary" />
              <q-btn type="submit" :label="isEdit ? '保存' : '创建'" color="primary" />
            </div>
          </q-form>
        </q-card-section>
      </q-card>
    </q-dialog>
  </q-page>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useQuasar } from 'quasar'

const $q = useQuasar()

// 表格列定义
const columns = [
  { name: 'select', label: '选择', field: '', align: 'center' },
  { name: 'configId', label: '参数ID', field: 'configId', align: 'center', sortable: true },
  { name: 'configName', label: '参数名称', field: 'configName', align: 'center', sortable: true },
  { name: 'configKey', label: '参数键名', field: 'configKey', align: 'center' },
  { name: 'configValue', label: '参数键值', field: 'configValue', align: 'center' },
  { name: 'configType', label: '系统内置', field: 'configType', align: 'center' },
  { name: 'createTime', label: '创建时间', field: 'createTime', align: 'center', sortable: true },
  { name: 'actions', label: '操作', align: 'center' },
]

// 系统内置选项
const configTypeOptions = [
  { label: '全部', value: '' },
  { label: '是', value: 'Y' },
  { label: '否', value: 'N' },
]

// 数据状态
const configs = ref([])
const selected = ref([])
const loading = ref(false)
const pagination = ref({
  page: 1,
  rowsPerPage: 10,
  rowsNumber: 0,
})
const searchForm = ref({
  configName: '',
  configKey: '',
  configType: '',
})
const dialogVisible = ref(false)
const isEdit = ref(false)
const configForm = ref({
  configId: null,
  configName: '',
  configKey: '',
  configValue: '',
  configType: 'N',
  remark: '',
})

// 初始化加载数据
onMounted(() => {
  onRequest({
    pagination: pagination.value,
    filter: searchForm.value,
  })
})

// 表格请求方法
function onRequest(props) {
  const { page, rowsPerPage } = props.pagination
  loading.value = true

  // 模拟API请求
  setTimeout(() => {
    // 这里应该是实际的API调用
    // 模拟数据
    const mockData = Array.from({ length: rowsPerPage }, (_, i) => ({
      configId: (page - 1) * rowsPerPage + i + 1,
      configName: [
        '主框架页-默认皮肤样式名称',
        '用户管理-账号初始密码',
        '主框架页-侧边栏主题',
        '账号自助-是否开启用户注册功能',
        '系统名称',
      ][i % 5],
      configKey: [
        'sys.index.skinName',
        'sys.user.initPassword',
        'sys.index.sideTheme',
        'sys.account.registerUser',
        'sys.name',
      ][i % 5],
      configValue: ['skin-blue', '123456', 'theme-dark', 'true', 'XX管理系统'][i % 5],
      configType: i % 3 === 0 ? 'Y' : 'N',
      createTime: new Date().toLocaleString(),
      remark: [
        '蓝色 skin-blue、绿色 skin-green、紫色 skin-purple、红色 skin-red、黄色 skin-yellow',
        '初始化密码 123456',
        '深色主题theme-dark，浅色主题theme-light',
        '是否开启注册用户功能（true开启，false关闭）',
        '系统名称',
      ][i % 5],
    }))

    // 应用查询条件
    let filteredData = [...mockData]
    if (props.filter.configName) {
      filteredData = filteredData.filter((item) =>
        item.configName.includes(props.filter.configName),
      )
    }
    if (props.filter.configKey) {
      filteredData = filteredData.filter((item) => item.configKey.includes(props.filter.configKey))
    }
    if (props.filter.configType) {
      filteredData = filteredData.filter((item) => item.configType === props.filter.configType)
    }

    configs.value = filteredData
    pagination.value.rowsNumber = filteredData.length
    pagination.value.page = page
    pagination.value.rowsPerPage = rowsPerPage
    loading.value = false
  }, 500)
}

// 查询处理
function handleSearch() {
  pagination.value.page = 1
  onRequest({
    pagination: pagination.value,
    filter: searchForm.value,
  })
}

// 重置查询
function resetSearch() {
  searchForm.value = {
    configName: '',
    configKey: '',
    configType: '',
  }
  handleSearch()
}

// 显示新增对话框
function showAddDialog() {
  isEdit.value = false
  configForm.value = {
    configId: null,
    configName: '',
    configKey: '',
    configValue: '',
    configType: 'N',
    remark: '',
  }
  dialogVisible.value = true
}

// 显示编辑对话框
function showEditDialog(row) {
  isEdit.value = true
  configForm.value = {
    ...row,
  }
  dialogVisible.value = true
}

// 提交表单
function submitForm() {
  // 这里应该是实际的API调用
  $q.notify({
    type: 'positive',
    message: isEdit.value ? '配置信息已更新' : '配置创建成功',
  })
  dialogVisible.value = false
  onRequest({
    pagination: pagination.value,
    filter: searchForm.value,
  })
}

// 确认删除
function confirmDelete(id) {
  $q.dialog({
    title: '确认删除',
    message: '确定要删除该配置吗？此操作不可恢复！',
    cancel: true,
    persistent: true,
  }).onOk(() => {
    // 这里应该是实际的API调用
    $q.notify({
      type: 'positive',
      message: '配置已删除',
    })
    onRequest({
      pagination: pagination.value,
      filter: searchForm.value,
    })
  })
}

// 批量删除
function confirmBatchDelete() {
  if (selected.value.length === 0) return

  // 检查是否包含系统内置配置
  const hasSystemConfig = selected.value.some((item) => item.configType === 'Y')
  if (hasSystemConfig) {
    $q.notify({
      type: 'negative',
      message: '不能删除系统内置配置',
    })
    return
  }

  $q.dialog({
    title: '确认批量删除',
    message: `确定要删除选中的 ${selected.value.length}  个配置吗？此操作不可恢复！`,
    cancel: true,
    persistent: true,
  }).onOk(() => {
    // 这里应该是实际的API调用
    $q.notify({
      type: 'positive',
      message: '已删除选中的配置',
    })
    selected.value = []
    onRequest({
      pagination: pagination.value,
      filter: searchForm.value,
    })
  })
}

// 导出数据
function exportData() {
  $q.notify({
    type: 'positive',
    message: '导出成功',
  })
}

// 刷新缓存
function refreshCache() {
  loading.value = true
  // 模拟API请求
  setTimeout(() => {
    $q.notify({
      type: 'positive',
      message: '配置缓存已刷新',
    })
    loading.value = false
  }, 1000)
}
</script>

<style lang="scss" scoped>
.q-table {
  thead tr th {
    font-weight: bold;
    background-color: #f5f5f5;
  }

  tbody tr:hover {
    background-color: #f5f5f5;
  }
}
</style>
